<?php

namespace App\Repository;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Customer\CustomerCoupon;
use App\Models\Promotion\Coupon;
use App\Models\Promotion\CouponAssignLog;
use App\Traits\DateTimeTrait;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

/**
 * 优惠券数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class CouponRepository extends BaseRepository
{
    use DateTimeTrait;
    /**
     * 保存数据
     *
     * @param array $data
     * @param int $couponId
     * @return int|mixed
     * @throws BusinessException
     */
    public function save(array $data, int $couponId = 0)
    {
        try {
            $query = $couponId ? Coupon::find($couponId) : new Coupon();
            foreach ($data as $field => $value) {
                $query->{$field} = $value;
            }
            return $query->save() ? $query->coupon_id : 0;
        } catch (\Exception $exception) {
            Log::error("[优惠券] 保存失败：{$exception->getMessage()}");
            throw new BusinessException(ResponseCode::SAVE_FAIL);
        }
    }

    /**
     * 优惠券列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(array $filter = [])
    {
        $query = Coupon::query()->orderByDesc('created_at');
        if(!empty($filter['name'])) {
            $query->where('name', 'like', '%' . $filter['name'] . '%');
        }
        if(!empty($filter['coupon_bn'])) {
            $query->where('coupon_bn', 'like', '%' . $filter['coupon_bn'] . '%');
        }
        if(!empty($filter['status'])) {
            $currTime = $this->getCurrDateTime();
            $query->where('start_at', '<=', $currTime)->where('end_at', '>=', $currTime);
        }
        return $query;
    }

    /**
     * 根据 Id 获取优惠券
     *
     * @param int $couponId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getById(int $couponId)
    {
        $query = Coupon::query()->where('coupon_id', $couponId)->first();
        $query->status_name = $this->getTimeRangeStatus($query->start_at, $query->end_at);
        return $query;
    }

    /**
     * 获取客户优惠券列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getMyList(array $filter = [])
    {
        $query = CustomerCoupon::query()->orderByDesc('created_at');
        if(!empty($filter['type'])) {
            switch ($filter['type'])
            {
                case 'unused':
                    $query->whereNull('used_at');
                    break;
                case 'used':
                    $query->whereNotNull('used_at');
                    break;
                case 'expired':
                    $query->where('end_at', '<', $this->getCurrDateTime());
                    break;
            }
        }
        if(!empty($filter['customer_id'])) {
            $query->where('customer_id', $filter['customer_id']);
        }
        if(!empty($filter['status'])) {
            switch ($filter['status'])
            {
                case 0:
                    // 已结束
                    $query->where('end_at', '<', $this->getCurrDateTime());
                    break;
                case 1:
                    // 进行中
                    $query->where('start_at', '<', $this->getCurrDateTime())->where('end_at', '>', $this->getCurrDateTime());
                    break;
            }
        }
        return $query;
    }
}
